//
//  QSWebViewController.m
//  QSSmarkPark-iOS
//
//  Created by 孙俊 on 2018/3/14.
//  Copyright © 2018年 QiSheng. All rights reserved.
//

#import "QSWebViewController.h"
#import "QSScriptMessageHandler.h"
#import "QSHomeInterface.h"

@interface QSWebViewController ()

@property (nonatomic, strong) UIBarButtonItem *backButtonItem;
@property (nonatomic, strong) UIBarButtonItem *closeButtonItem;
@property (nonatomic, strong) UIBarButtonItem *shareButtonItem;

@property (nonatomic, strong) NSArray *h5MethodsNameArray;
@property (nonatomic, strong) NSDictionary *h5ShareDic;

@end

@implementation QSWebViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:self.isHideNavigationBar animated:animated];
    if (self.isHideNavigationBar) {
        self.webView.frame = kScreenBounds;
        self.webView.realWebView.frame = self.webView.bounds;
        self.webView.loadingView.frame = self.webView.bounds;
    }
    
}

- (instancetype)init {
    if (self = [super init]) {
        _showLoadingAnimation = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupWebView];
}

- (void)setupWebView {
    _webView = [[QSWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavgationBarHeight)];
    _webView.showProgressView = !_showLoadingAnimation;
    [_webView showLoadingView:_showLoadingAnimation];
    
    if (self.URLString) {
        [_webView loadRequest:[NSURLRequest requestWithURL:[self.URLString noChineseUrl]]];
        DLog(@"URLString:%@",[self.URLString noChineseUrl]);
    } else if (self.HTMLString) {
        [_webView loadHTMLString:self.HTMLString baseURL:nil];
    }
    _webView.delegate = self;
    [self.view addSubview:_webView];
    if (kDevice_Is_iPhoneX) {
        [self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.view);
            make.top.equalTo(self.view).offset(kRealValue(kStatusBarHeight));
            make.width.equalTo(self.view);
            make.bottom.equalTo(self.view);
        }];
    }

    //注册H5方法
    QSScriptMessageHandler * messageHandler = [QSScriptMessageHandler scriptWithDelegate:self];
    for (NSString *methodName in self.h5MethodsNameArray) {
        [_webView addScriptMessageHandler:messageHandler name:methodName];
    }
    
    self.navigationItem.leftBarButtonItem = self.backButtonItem;
}

#pragma mark - **************** Private Methods
- (void)showLeftCloseItem:(BOOL)isShow {
    if (isShow) {
        [self.navigationItem setLeftBarButtonItems:@[self.backButtonItem, self.closeButtonItem]];
    } else {
        [self.navigationItem setLeftBarButtonItems:@[self.backButtonItem]];
    }
}

#pragma mark - **************** Events
- (void)shareButtonItemClicked {
    [self Share:self.h5ShareDic];
}

- (void)navCloseButtonDown {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)back {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - **************** H5交互方法
- (void)webPush:(NSDictionary *)tempDic {
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    DLog(@"%@",tempDic);
}

- (void)GoBack:(NSDictionary *)tempDic {
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)ShareCode:(NSDictionary *)tempDic {
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    DLog(@"%@",tempDic);
    if (tempDic) {
        self.h5ShareDic = tempDic;
        self.navigationItem.rightBarButtonItem = self.shareButtonItem;
    }
}

- (void)Share:(NSDictionary *)tempDic {
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSString *title = tempDic[@"title"];
    NSString *content = tempDic[@"content"];
    NSString *imageURL = tempDic[@"imageUrl"];
    NSString *url = tempDic[@"url"];
    
//    [[QSShareHelper sharedHelper] shareWebPageWithTitle:title
//                                                    des:content
//                                                    url:url
//                                               imageURL:imageURL
//                                             completion:^(id result, NSError *error)
//     {
//     }];
}

- (void)toggleClose:(NSDictionary *)tempDic {
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSNumber *isShowCloseItem = tempDic[@"show"];
    [self showLeftCloseItem:isShowCloseItem.boolValue];
}

- (void)themeColor:(NSDictionary *)tempDic {
    if (![tempDic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    NSString *hexColor = tempDic[@"color"];
    UIColor *endColor = [UIColor colorWithHexString:hexColor];
    
//    UIColor *transColor = [UIColor getColorWithColor:[UIColor QSColorBlue3569FF] andCoe:1 andEndColor:endColor];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithFrame:CGRectMake(0, 0, kScreenWidth, kNavgationBarHeight) color:transColor] forBarMetrics:UIBarMetricsDefault];
//    self.webView.progressViewColor = transColor;
}

#pragma mark - **************** SJWebViewDelegate
- (void)webViewDidStartLoad:(QSWebView *)webView {
    [self.view configBlankPage:BlankPageViewTypeWebView
                       hasData:YES
                      hasError:NO
             reloadButtonBlock:nil];
}

- (void)webViewDidFinishLoad:(QSWebView *)webView {
    [_webView showLoadingView:NO];

    DLog(@"title:%@",webView.title);
    [self setupNavgationBarTitle:webView.title];
    @weakify(self);
    webView.titleDidChangeBlock = ^(NSString * _Nonnull title) {
        @strongify(self);
        if (title.length) {
            [self setupNavgationBarTitle:title];
        }
    };
}

- (void)webView:(QSWebView *)webView didFailLoadWithError:(NSError *)error {
    [_webView showLoadingView:NO];

    @weakify(self);
    [self.view configBlankPage:BlankPageViewTypeWebView
                       hasData:NO
                      hasError:YES
             reloadButtonBlock:^(id sender)
     {
         @strongify(self);
         // 进来时没有网络连接进来后有网的时候 直接reload加载不出网页 需要重新loadRequest
         [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString]]];
     }];
}

- (void)webView:(QSWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    [self showLeftCloseItem:webView.canGoBack];
}

#pragma mark - **************** WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    DLog(@"name:%@:\n body:%@",message.name, message.body);
    SEL selector = NSSelectorFromString([NSString stringWithFormat:@"%@:",message.name]);
    if (selector && [self respondsToSelector:selector]) {
        SuppressPerformSelectorLeakWarning([self performSelector:selector withObject:message.body]);
    }
}

#pragma mark - **************** Setter Getter
- (UIBarButtonItem *)backButtonItem {
    if (_backButtonItem == nil) {
        _backButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_navigation_back"] target:self action:@selector(back)];
    }
    return _backButtonItem;
}

- (UIBarButtonItem *)closeButtonItem {
    if (_closeButtonItem == nil) {
        _closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" font:[UIFont QSFontOfSize15] titleColor:[UIColor QSColorWhiteFFFFFF] target:self action:@selector(navCloseButtonDown)];
    }
    return _closeButtonItem;
}

- (UIBarButtonItem *)shareButtonItem {
    if (_shareButtonItem == nil) {
        _shareButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" font:[UIFont QSFontOfSize15] titleColor:[UIColor QSColorWhiteFFFFFF] target:self action:@selector(shareButtonItemClicked)];
    }
    return _shareButtonItem;
}

- (NSArray *)h5MethodsNameArray {
    return @[@"Share",@"GoBack",@"webPush",@"themeColor",@"toggleClose",@"ShareCode"];
}

- (void)dealloc {
    for (NSString *methodName in self.h5MethodsNameArray) {
        [[_webView.realWebView configuration].userContentController removeScriptMessageHandlerForName:methodName];
    }
}

@end


